package com.chuzhiyun.chengguoxy.feature.login;

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import com.chuzhiyun.chengguoxy.R;
import com.chuzhiyun.chengguoxy.databinding.ActivityLoginBinding;
import com.chuzhiyun.chengguoxy.feature.base.BaseActivity;
import com.chuzhiyun.chengguoxy.feature.bean.OnePassResultBean;
import com.chuzhiyun.chengguoxy.feature.bean.UserInfoBean;
import com.chuzhiyun.chengguoxy.feature.home.HomeActivity;
import com.chuzhiyun.chengguoxy.global.Config;
import com.chuzhiyun.chengguoxy.global.MyApplication;
import com.chuzhiyun.chengguoxy.global.Status;
import com.chuzhiyun.chengguoxy.network.NetApi;
import com.chuzhiyun.chengguoxy.network.NetService;
import com.chuzhiyun.chengguoxy.network.StringNetCallback;
import com.chuzhiyun.chengguoxy.utlis.CustomClickListener;
import com.chuzhiyun.chengguoxy.wxapi.AnyEventType;
import com.google.gson.Gson;
import com.hjq.toast.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cookie.store.CookieStore;
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.vondear.rxtool.RxSPTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.List;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

public class LoginActivity extends BaseActivity<ActivityLoginBinding> {

    private PhoneNumberAuthHelper mPhoneNumberAuthHelper;
    private String mPhoneNumber;
    @Override
    public void initView(View view) {
        EventBus.getDefault().register(this);
        viewBinding.submitText.setEnabled(false);
    }

    @Override
    public void initData() {

    }

    @Override
    public void setListener() {
        viewBinding.onePassText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                showLoadingDialog();
                createLogin();
            }
        });
        viewBinding.ivWeixin.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                WeiChatLogin();
            }
        });
        viewBinding.editPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (viewBinding.editPhone.getText().length()==11){
                    viewBinding.submitText.setBackgroundResource(R.drawable.login_btn);
                    viewBinding.submitText.setEnabled(true);
                    mPhoneNumber = viewBinding.editPhone.getText()+"";
                }else {
                    viewBinding.submitText.setBackgroundResource(R.drawable.login_btnnor);
                    viewBinding.submitText.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        viewBinding.submitText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                loginClick();
            }
        });
    }

    private void WeiChatLogin(){
        SendAuth.Req req = new SendAuth.Req();
        req.scope = Config.reqScope;
        req.state = Config.reqState;
        Status.wxMode = Config.WX_LOGIN_BIND;
        MyApplication.mWxApi.sendReq(req);
    }

    private void  createLogin(){
        TokenResultListener mTokenResultListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                System.out.println(s);
                Gson gson = new Gson();
                OnePassResultBean bean = gson.fromJson(s,OnePassResultBean.class);
                if (bean.getCode().equals("600001")){
                    //唤起授权页成功
                    dismissLoadingDialog();
                }
                if (bean.getCode().equals("600000")){
                    //获取token成功
                    dismissLoadingDialog();

                    CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
                    cookieStore.removeAllCookie();

                    String  mobileToken = bean.getToken();
                    String url = NetApi.postLoginOnePass();
                    HashMap<String,String>param = new HashMap<>();
                    param.put("mobileToken",mobileToken);
                    NetService.getInstance().postParam(url, param, new StringNetCallback() {
                        @Override
                        public void onSuccess(String response, int statusCode) throws Exception {
                            System.out.println(response);
                            if (statusCode==204){
                                mPhoneNumberAuthHelper.quitLoginPage();
                                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                                finish();
                                getUserInfo();
                            }
                            //noinspection StatementWithEmptyBody
                            if (statusCode==403){

                            }
                        }

                        @Override
                        public void onError(String error) {
                            System.out.println(error);
                        }
                    });

                }

                mPhoneNumberAuthHelper.hideLoginLoading();
            }

            @Override
            public void onTokenFailed(String s) {
                System.out.println(s);
                dismissLoadingDialog();
                ToastUtils.show("请求超时");
            }
        };

        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenResultListener);
        mPhoneNumberAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
                .setAppPrivacyOne("《自定义隐私协议》", "https://test.h5.app.tbmao.com/user")
                .setAppPrivacyTwo("《百度》", "https://www.baidu.com")
                .setAppPrivacyColor(Color.GRAY, Color.parseColor("#000000"))
                .setNavHidden(true)
                .setLogoImgPath(String.valueOf(R.mipmap.mytel_app_launcher))
                .setSloganText("这是提示的文字内容")
                .setLogBtnText("一键登录2333")
                .setLogBtnHeight(44)
                .setLogBtnTextSizeDp(12)
                .setLogBtnTextColor(Color.parseColor("#000000"))
                .setSwitchAccHidden(false)
                .setSwitchAccText("其他方式登录")
                .setSwitchAccTextSizeDp(12)
                .create());

        mPhoneNumberAuthHelper.addAuthRegisterXmlConfig(new AuthRegisterXmlConfig.Builder()
                .setLayout(R.layout.login_other, new AbstractPnsViewDelegate() {
                    @Override public void onViewCreated(View view) {
                        //这⾥返回的View，不建议⽤强引⽤，如果要⽤，请及时释放，否则容易造成内存泄 漏
//                        findViewById(R.id.xxxx).setOnClickListener(new View.OnClickL istener() {
//                            @Override public void onClick(View v) {
//                                //do something
//                            }
//                        });
                    }
                })
                .build());
        mPhoneNumberAuthHelper.getReporter().setLoggerEnable(true);
        mPhoneNumberAuthHelper.setAuthSDKInfo(Config.ALPhone_code);
        mPhoneNumberAuthHelper.getLoginToken(this,3000);
    }

    private void loginClick(){
        Intent intent = new Intent();
        intent.setClass(mContext,SmsCodeActivity.class);
        intent.putExtra("mPhoneNumber",mPhoneNumber);
        startActivity(intent);
    }

    private void getUserInfo(){

        saveToken();
        String url = NetApi.getStudentInfo();
        NetService.getInstance().get(url, new StringNetCallback() {
            @Override
            public void onSuccess(String response, int statusCode) throws Exception {
                System.out.println(response);
                if (statusCode==200){
                    Gson gson = new Gson();
                    UserInfoBean bean = gson.fromJson(response,UserInfoBean.class);
                    System.out.println(bean);
                }
            }

            @Override
            public void onError(String error) {
                System.out.println(error);
            }
        });
    }

    private void saveToken(){
        CookieStore cookieStore = OkGo.getInstance().getCookieJar().getCookieStore();
        System.out.println(cookieStore);

        List<Cookie> cookies = cookieStore.getCookie(HttpUrl.parse(NetApi.Base_URL));
        Cookie cookie = cookies.get(0);
        System.out.println(cookie);
        String token = cookie.value();
        System.out.println(token);
        RxSPTool.putString(MyApplication.getmContext(),Config.SP_TOKEN,token);
    }

    @Subscribe
    public void onEvent(AnyEventType event) {
        System.out.println("hello");
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected ActivityLoginBinding getViewBinding() {
        return ActivityLoginBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }
}